
from datetime import datetime

import openpyxl
import win32con
import win32gui
from bs4 import BeautifulSoup  # 网页解析，数据获取
import json
import requests
import message
import warnings
import win32clipboard
from PIL import Image
import io
import os
import ctypes
from ctypes import wintypes
warnings.filterwarnings('ignore')

STATUS=0#标记通知，只添加一次
studata=[]#标记完课数据，只输出一种

# 定义OPENFILENAME结构体
class OPENFILENAME(ctypes.Structure):
    _fields_ = [
        ("lStructSize", wintypes.DWORD),
        ("hwndOwner", wintypes.HWND),
        ("hInstance", wintypes.HINSTANCE),
        ("lpstrFilter", wintypes.LPCWSTR),
        ("lpstrCustomFilter", wintypes.LPWSTR),
        ("nMaxCustFilter", wintypes.DWORD),
        ("nFilterIndex", wintypes.DWORD),
        ("lpstrFile", wintypes.LPWSTR),
        ("nMaxFile", wintypes.DWORD),
        ("lpstrFileTitle", wintypes.LPWSTR),
        ("nMaxFileTitle", wintypes.DWORD),
        ("lpstrInitialDir", wintypes.LPCWSTR),
        ("lpstrTitle", wintypes.LPCWSTR),
        ("Flags", wintypes.DWORD),
        ("nFileOffset", wintypes.WORD),
        ("nFileExtension", wintypes.WORD),
        ("lpstrFile", wintypes.LPWSTR),  # 需要宽字符指针类型
        ("lCustData", wintypes.LPARAM),
        ("lpfnHook", wintypes.LPVOID),
        ("lpTemplateName", wintypes.LPCWSTR),
        ("pvReserved", wintypes.LPVOID),
        ("dwReserved", wintypes.DWORD),
        ("FlagsEx", wintypes.DWORD),
    ]


def select_image_path():
    """使用结构体传递参数，兼容所有pywin32版本"""
    # 初始化结构体
    ofn = OPENFILENAME()
    ofn.lStructSize = ctypes.sizeof(OPENFILENAME)
    ofn.hwndOwner = win32gui.GetDesktopWindow()  # 父窗口句柄
    ofn.lpstrTitle = "选择图片"  # 对话框标题

    # 文件过滤器（使用分号分隔，空字符结尾）
    filter_buffer = ctypes.create_unicode_buffer(
        "图片文件 (*.png;*.jpg;*.jpeg;*.bmp)\0"
        "*.png;*.jpg;*.jpeg;*.bmp\0"
        "所有文件 (*.*)\0"
        "*.*\0"
    )
    ofn.lpstrFilter = ctypes.cast(filter_buffer, ctypes.c_wchar_p)  # 转换为宽字符指针
    ofn.nFilterIndex = 1  # 默认选中第一个过滤器

    # 文件名缓冲区
    buffer_size = 2048
    ofn.lpstrFile = ctypes.create_unicode_buffer(buffer_size)
    ofn.nMaxFile = buffer_size

    # 对话框标志
    ofn.Flags = (win32con.OFN_FILEMUSTEXIST |
                 win32con.OFN_PATHMUSTEXIST |
                 win32con.OFN_HIDEREADONLY)

    # 调用API（只传递一个结构体参数）
    try:
        # 使用user32.dll中的原生函数
        if ctypes.windll.comdlg32.GetOpenFileNameW(ctypes.byref(ofn)):
            path = ofn.lpstrFile.value
            return path if os.path.isfile(path) else ""
        return ""
    except Exception as e:
        print(f"文件选择出错: {e}")
        return ""


def copy_image_to_clipboard(image_path):
    try:
        # 使用PIL打开图片
        with Image.open(image_path) as image:
            # 转换为RGB模式确保兼容性
            image_rgb = image.convert("RGB")

            # 将图片保存为BMP格式到内存字节流
            output = io.BytesIO()
            image_rgb.save(output, format="BMP")
            bmp_data = output.getvalue()[14:]  # 移除BMP文件头（前14字节）

            # 写入剪贴板
            win32clipboard.OpenClipboard()
            try:
                win32clipboard.EmptyClipboard()
                # 使用CF_DIB格式（设备无关位图）
                win32clipboard.SetClipboardData(win32clipboard.CF_DIB, bmp_data)
                return True
            finally:
                win32clipboard.CloseClipboard()

    except Exception as e:
        print(f"复制图片失败: {e}")
        return False




def readtxt(add):
    txt_tables = []
    f = open(add, "r",encoding='utf-8')
    line = f.readline() #
    while line:
        #txt_data = eval(line) # 可将字符串变为元组
        txt_tables.append(line.replace('\n', '').replace('\r', '').replace(" ",'')) # 列表增加
        line = f.readline() #
    #print(txt_tables)
    return txt_tables

def writetxt(add,txt):
    f = open(add, "a",encoding='utf-8')
    f.write(str(txt))
    f.close()


# 获取当前活动工作表（默认为第一张）

def read(arr):
    # 打开 Excel 文件
    workbook = openpyxl.load_workbook("1.xlsx")
    sheet = workbook[arr[2]]
    cell_value = sheet.cell(row=int(arr[0]), column=int(arr[1])).value

    return cell_value
def readformatdata(arr):
    #print(arr)
    arr1 = [0,0,0,0]
    if arr[0] == "莫顿思维" or arr[0] == "两课思维" or arr[0]=="C1":
        arr1[0]=arr[0]
        if (int(arr[1]) == 1):
            arr1[2]=arr[2];
        else:
            arr1[2]=(int(arr[1])-1) * 4+int(arr[2])

    else:
        arr1[0]=arr[0]
        if (int(arr[1]) == 1):
            arr1[2]=arr[2];
        else:
            arr1[2]=(int(arr[1])-1) * 7+int(arr[2])
    return  read([int(arr[3]), arr1[2], arr[0]])


#formatdata("两课思维+5+1+4".split("+"))
#         https://crm.hetao101.com/crm-homework/v2/comment/stats/teacher?teacherId=30007523&querySubjectId=21
HOMEWORK="https://crm.hetao101.com/crm-homework/v2/comment/stats/teacher?querySubjectId=21&teacherId="
CLASS="https://crm.hetao101.com/tutor-learning-follow/v1/schedule/scheduleQuery?counselorId="
SCHEDULE="https://crm.hetao101.com/tutor-learning-follow/v1/finishClass/rate/overview?dataVersion=3&classId="
TEACHERNAME="https://crm.hetao101.com/crm-api/v1/class?current=1&pageSize=10&counselorId="
Student="https://crm.hetao101.com/tutor-learning-follow/v1/finishClass/detail/list/export?classId={0}&dataVersion=3&learningProgressStr=1%2C2&courseLevelStr={1}&isOnlyInClass=true&courseLevel=8&unitSequenceStr={1}&learningProgress=2&showTheLatitudes=1%2C2%2C3%2C4%2C5"
#Student="https://crm.hetao101.com/tutor-learning-follow/v1/finishClass/detail/list/export?classId={0}&dataVersion=3&learningProgressStr=1%2C2&courseLevelStr={1}&isOnlyInClass=true&courseLevel=1&unitSequenceStr={1}&learningProgress=2&showTheLatitudes=1%2C2%2C3%2C4%2C5"
class Foo(object):
    classid = []
    classname = []
    classtime = []
    classunit = []

def getData(url):
    #Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
    head = {"user-agent": "jianglai-hetaojia"}
    #print("Dataurl:"+url)
    req = requests.get(url=url, headers=head)
    req.encoding = 'UTF-8'
    # 解析得到网站的信息
    soup = BeautifulSoup(req.text, 'html.parser')
    return soup

    #print(data)

#获取作业
def getHomework(url):
    data = getData(url).text
    #print(data)
    a=[]
    for i in range(0, 6):
        if i==1 or i==2:
            continue
        a.append(json.loads(data)['data']["list"][i]['count'])
    return a

#获取班级开课情况
def getClass(url):
    data = getData(url).text
    classes=json.loads(data)["data"]

    for i in range(len(classes)):
        for j in range(len(classes[i])):
            if not classes[i][j]:
                continue
            else:
                Foo.classid.append(classes[i][j][0]['classId'])
                Foo.classname.append(classes[i][j][0]['className'])
                Foo.classtime.append(classes[i][j][0]['formatTime'])
                Foo.classunit.append(classes[i][j][0]['courseAndUnit'])
                #print(classes[i][j][0])


 #获取完课情况
def getschedule(url):
    global studata
    data = getData(url).text
    time=json.loads(data)["data"]["levelUnitRate"]
    datas=json.loads(data)["data"]
    a=[]#完课率，完课人数，未到课，未完课

    a.append(datas["curFinishClassRate"])
    a.append(datas["finishCnt"])
    a.append(datas["noFinishCnt"])
    a.append(datas["noAttendanceCnt"])
    a.append("%s-%s"%(datas["curCourseLevel"],datas["curUnitSequence"]))
    #print("首次输出")
    if studata==a:
        #print("多次输出")
        return
    studata=a
    return a

def getAll(stri):
    global STATUS
    Foo.classid=[]
    Foo.classname = []
    msgtext = []
    b=getHomework(HOMEWORK+stri)
    #print("作业剩余%s,超24：%s,超48：%s，超72：%s"%(b[0],b[1],b[2],b[3]))

    getClass(CLASS + stri)
    msgarr = []
    msgarr.append(["作业剩余%s,超24：%s,超48：%s，超72：%s"%(b[0],b[1],b[2],b[3])])
    banji=[]
    for i in range(len(Foo.classid)):
        a=getschedule(SCHEDULE+str(Foo.classid[i]))
        if a is None:
            continue
        #print(a)
        index=Foo.classname[i].find('第')+1
        data = []
        data.append("本%s,%s开课，目前%s完课率为：%s"%(Foo.classname[i][0:4],Foo.classname[i][4]+Foo.classname[i][index:index+1],a[4],a[0])+"%<br>")
        data.append("完课人数%s，到课未完课%s，未到课%s" % (a[1], a[2], a[3]))

        msgtext.append(getStudents([str(Foo.classid[i]),a[4].split("-")[0]]))
        banji.append(data)
        if a[1]==0 and a[2]==0 and a[3]==0:
            continue
    msgarr.append(banji)
    msgarr.append(msgtext)
    week=[]
    for i in Foo.classname:
        if i[1]=='四':
            week.append('3')
        if i[1]=='五':
            week.append('4')
        if i[1]=='六':
            week.append('5')
    if STATUS==0:
        message.addjob(week)
        STATUS=1
    return msgarr

#获取老师花名
def getTeacherName(stri):
    data=getData(TEACHERNAME+stri).text
    name=json.loads(data)["data"]['classInfoVoPageResponse']['data'][0]['counselorName']
    if name[0]=="V":
        name=name.replace("VIP服务工程师","")+"老师"
    if name[0:3]=="林襄阳":
        name = "美丽漂亮温柔动人的襄阳小仙女"
    if name[0:2] == "罗曼":
        name = "美丽漂亮温柔动人的襄阳小仙女"
    return name

# 获取所有未到课学员名字arr[0]班级id，arr[1]阶段数
def getStudents(arr):
    #print(arr)
    students = []
    head = {"user-agent": "jianglai-hetaojai"}
    req = requests.get(url=Student.format(arr[0], arr[1]), headers=head)
    with open("res/wk.xlsx", "wb") as code:
        code.write(req.content)
    workbook = openpyxl.load_workbook('res/wk.xlsx')
    sheet = workbook.active
    cell = sheet['B']
    for i in cell:
        students.append(i.value)
    return ",".join(students[3:])

def getai(a):
    url = 'https://api.ownthink.com/bot?appid=9ffcb5785ad9617bf4e64178ac64f7b1&spoken=%s' % a
    try:
        te = requests.get(url).json()
        data = te['data']['info']['text']
    except Exception as e:
        return "脑子宕机了，让我缓缓。。。"

    return data

oj_login_url = "http://82.157.207.59/login.php"
def getstatus(temp_data,start_time):
    # temp_data = {
    #     "user_id": "elk638798",
    #     "password": "Elk638798"
    # }
    global oj_headers
    global com_headers
    req = requests.post(oj_login_url, data=temp_data)
    req_cookie = requests.utils.dict_from_cookiejar(req.cookies)
    oj_cookie=''
    for key in req_cookie:
        oj_cookie += '{0}={1};'.format(key, req_cookie[key])
    #oj_submit_url = "http://82.157.207.59/status.php?problem_id=&user_id=elk638798&language=1&jresult=-1"

    oj_headers = {
        'Cookie': oj_cookie,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67'
    }

    # req = requests.get(oj_submit_url, headers=oj_headers)
    # soup = BeautifulSoup(req.text, 'html.parser')
    # table = soup.find('table')
    # ans = []
    # for row in table.find_all('tr')[1:]:
    #     cells = row.find_all('td')
    #     result = cells[3].text.strip()
    #     name = cells[7].text.strip()
    #     level = cells[6].text.strip()
    #     time = cells[8].text.strip()
    #     ans.append([name, level, result, time])
    # return(ans)

    oj_find_url = "http://82.157.207.59/status.php?user_id="+temp_data["user_id"]
    r = requests.get(oj_find_url, headers=oj_headers)
    soup = BeautifulSoup(r.text, 'html.parser')
    table = soup.find('table')

    ans = []
    start_id = 0
    for row in table.find_all('tr')[1:]:
        cells = row.find_all('td')
        id = cells[0].text.strip()
        start_id = id
    base_url = "http://82.157.207.59/status.php?8&top={}&prevtop={}&user_id={}"
    limit_pre_age = 50
    max_page = 50
    flag = True
    for page_num in range(max_page):
        offset = page_num * limit_pre_age + int(start_id)
        url = base_url.format(offset, offset + limit_pre_age - 1,temp_data["user_id"])
        response = requests.get(url, headers=oj_headers)
        if response.status_code == 200 and flag == True:
            soup = BeautifulSoup(r.text, 'html.parser')
            table = soup.find('table')
            for row in table.find_all('tr')[1:]:
                cells = row.find_all('td')
                id = cells[0].text.strip()
                us_id = cells[1].text.strip()
                result = cells[3].text.strip()
                name = cells[7].text.strip()
                level = cells[6].text.strip()
                ti = cells[8].text.strip()
                #print(us_id, temp_data["user_id"])
                start_id = id
                ti = datetime.strptime(ti, '%Y-%m-%d %H:%M:%S')
                ti=str(ti)
                #print(ti<start_time)
                if ti < start_time:
                    flag = False
                    break
                if us_id == temp_data["user_id"]:
                    ans.append([name, level, result, ti])
                # if True:
                #     break
    return ans

#getAll("30009321")
# temp_data = {
#     "user_id": 'elk638798',
#     "password": 'Elk638798'
# }
# print(getstatus(temp_data))
